package com.sylingd.blog.activity

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.Toolbar
import android.widget.ListView
import android.widget.SimpleAdapter
import android.widget.TextView
import com.google.gson.JsonParser
import com.sylingd.blog.BaseApplication
import com.sylingd.blog.R
import java.nio.charset.Charset
import java.util.*

class AboutActivity : AppCompatActivity() {

	private lateinit var osView: ListView
	private val osData = ArrayList<Map<String, Any>>()

	companion object {
		fun launch(context: Activity) {
			val intent = Intent(context, AboutActivity::class.java)
			context.startActivity(intent)
		}
	}

	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)

		setContentView(R.layout.activity_about)
		val toolbar = findViewById<Toolbar>(R.id.toolbar)
		setSupportActionBar(toolbar)

		supportActionBar?.setDisplayHomeAsUpEnabled(true)
		toolbar.setNavigationOnClickListener {
			finish()
		}

		BaseApplication.initSlidr(this)

		osView = findViewById(R.id.openSource)
		osView.adapter = SimpleAdapter(this,
				osData,
				android.R.layout.simple_list_item_2,
				arrayOf("title", "text"),
				arrayOf(android.R.id.text1, android.R.id.text2).toIntArray())
		osView.setOnItemClickListener { _, _, position, _ ->
			val intent = Intent(Intent.ACTION_VIEW, Uri.parse(osData[position]["url"].toString()))
			startActivity(intent)
		}

		//设置版本号文字
		val pkgInfo = packageManager.getPackageInfo(packageName, 0)
		val version = findViewById<TextView>(R.id.version)
		version.text = pkgInfo.versionName + "(" + pkgInfo.versionCode + ")"

		//加载开源列表
		Thread({
			loadOpenSource()
		}).start()
	}

	private fun loadOpenSource() {
		val res = assets.open("opensource.json")
		val buffer = ByteArray(res.available())
		res.read(buffer)
		val result = JsonParser().parse(String(buffer, Charset.forName("utf8"))).asJsonArray
		result.forEach {
			val d = it.asJsonObject
			val item = HashMap<String, String>()
			item["title"] = d.get("title").asString
			item["text"] = d.get("license").asString
			item["url"] = d.get("url").asString
			osData.add(item)
		}
		(osView.adapter as SimpleAdapter).notifyDataSetChanged()
	}
}
